package com.dongdongshop.service.impl;

import com.dongdongshop.admin.model.TbBrand;
import com.dongdongshop.admin.model.TbBrandExample;
import com.dongdongshop.admin.vo.TbBrandVO;
import com.dongdongshop.aop.DKLog;
import com.dongdongshop.em.PageRequest;
import com.dongdongshop.em.PageResult;
import com.dongdongshop.mapper.TbBrandMapper;
import com.dongdongshop.service.BrandService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    private TbBrandMapper brandMapper;

    @Override
    @DKLog
    public PageResult brandList(PageRequest<TbBrandVO> tbBrandVO) {
        //获取前台传来的条件查询
        TbBrandVO vo = tbBrandVO.getParms();
        TbBrandExample e = new TbBrandExample();
        TbBrandExample.Criteria criteria = e.createCriteria();
        //调用lang3依赖判断前段传来的条件是否为空
        if (StringUtils.isNotBlank(vo.getName())) {
            criteria.andNameLike("%"+vo.getName()+"%");
        }
        if (StringUtils.isNotBlank(vo.getFirstChar())) {
            criteria.andFirstCharEqualTo(vo.getFirstChar());
        }
        PageHelper.startPage(tbBrandVO.getPageNum(),tbBrandVO.getPageSize());
        List<TbBrand> brands = brandMapper.selectByExample(e);
        PageInfo info = new PageInfo(brands);
        List<TbBrandVO> collect1 = brands.stream().map(l -> {
            TbBrandVO vo1 = new TbBrandVO();
            BeanUtils.copyProperties(l, vo1);
            return vo1;
        }).collect(Collectors.toList());
        return new PageResult(tbBrandVO.getPageNum(),tbBrandVO.getPageSize(), info.getTotal(), collect1,3);
    }

    @Override
    public void add(TbBrandVO brandVO) {
        TbBrand brand = new TbBrand();
        BeanUtils.copyProperties(brandVO, brand);
        brandMapper.insertSelective(brand);
    }

    @Override
    public TbBrandVO getById(Long id) {
        TbBrandVO vo = new TbBrandVO();
        TbBrand tbBrand = brandMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(tbBrand, vo);
        return vo;
    }

    @Override
    public void update(TbBrandVO brandVO) {
        TbBrand brand = new TbBrand();
        BeanUtils.copyProperties(brandVO, brand);
        brandMapper.updateByPrimaryKeySelective(brand);
    }

    @Override
    public void delete(Long[] ids) {
        TbBrandExample example = new TbBrandExample();
        TbBrandExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(Arrays.asList(ids));
        brandMapper.deleteByExample(example);
    }
}
